#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <functional>
#include "Log.hpp"
#include "InetAddr.hpp"

using namespace LogModule;

using func_t = std::function<void(int,const std::string& word,const InetAddr&)>;

class UdpServer
{
public:
    UdpServer(uint16_t port,func_t func)
    :_port(port)
    ,_running(false)
    ,_func(func)
    {}
    void Init()
    {
        // 1. 创建套接字
        _sockfd = socket(AF_INET,SOCK_DGRAM,0);
        if(_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket error!";
            exit(1);
        }
        LOG(LogLevel::INFO) << "socket success, sockfd: " << _sockfd;

        // 2. 给sockfd,绑定IP和端口号
        struct sockaddr_in server;
        memset(&server,0,sizeof(server)); // 初始化server
        server.sin_family = AF_INET;
        server.sin_port = htons(_port); // struct sockaddr_in里面必须是大端存储
        server.sin_addr.s_addr = INADDR_ANY; // INADDR,是0，无所谓大小端

        int n = bind(_sockfd,(struct sockaddr*)&server,sizeof(server));
        if(n < 0)
        {
            LOG(LogLevel::FATAL) << "bind error!";
            exit(2);
        }
        LOG(LogLevel::INFO) << "bind success, sockfd: "<< _sockfd;
    }
    
    void Start()
    {
        _running = true;

        while(_running) // 一直运行
        {
            // 1. 收消息
            char buf[128];
            struct sockaddr_in addr;
            memset(&addr,0,sizeof(addr));
            socklen_t len = sizeof(addr);
            ssize_t s = recvfrom(_sockfd,buf,sizeof(buf)-1,0,(struct sockaddr*)&addr,&len);
            if(s > 0)
            {
                buf[s] = 0;
                // 2. 推送任务
                InetAddr client(addr);
                _func(_sockfd,buf,client);
            }
        }
    }

    ~UdpServer()
    {
        int n = close(_sockfd);
        if(n < 0)
            LOG(LogLevel::INFO) << "close socket "<< _sockfd <<" error!";
        LOG(LogLevel::INFO) << "close socket "<< _sockfd <<" success";
    }
private:
    int _sockfd;
    uint16_t _port;
    bool _running;
    func_t _func;
};